<template>
    <div class="container">
        <div class="userinfo">
            <img class="userinfo-avatar" v-if="userInfo.avatarUrl" :src="userInfo.avatarUrl" background-size="cover" />
        </div>
        <div v-if="isLogin" class="userinfo-nickname">
            欢迎, {{ userInfo.nickName }}!
        </div>

        <mp-button v-if="!isLogin" type="default" size="large" btnClass="mb15" openType="getUserInfo" @getuserinfo="authorizedLogin">授权登录</mp-button>
    </div>
</template>

<script>
  import mpButton from 'mpvue-weui/src/button'
  export default {
    name: 'login',
    data () {
      return {
        isLogin: false,
        userInfo: {}
      }
    },
    components: {
      mpButton
    },
    methods: {
      // 获取用户信息
      getUserInfo () {
        // 调用登录接口
        wx.login({
          success: () => {
            wx.getUserInfo({
              success: (res) => {
                // 成功授权
                this.userInfo = res.userInfo
                this.isLogin = true
              }
            })
          }
        })
      },
      // 调起微信授权接口
      authorizedLogin (data) {
        this.getUserInfo()
      }
    },
    created () {
      // 调用应用实例的方法获取全局数据
      this.getUserInfo()
    }
  }
</script>

<style scoped>
    .userinfo {
        display: flex;
        flex-direction: column;
        align-items: center;
    }
    .userinfo-avatar {
        width: 128rpx;
        height: 128rpx;
        margin: 20rpx;
        border-radius: 50%;
    }
    .userinfo-nickname {
        color: #aaa;
    }
</style>
